#!/usr/bin/env python
# -*- coding: utf-8 -*-


import streamlit as st
import pandas as pd
from io import BytesIO
import threading
import time

# 用于存储锁状态的全局变量
lock = threading.Lock()
lock_timeout = 60  # 锁超时时间（秒）
lock_timestamp = None

def check_lock():
    global lock, lock_timestamp
    if lock.locked():
        if time.time() - lock_timestamp > lock_timeout:
            lock.release()
            return False
        return True
    return False

def acquire_lock():
    global lock, lock_timestamp
    if check_lock():
        st.warning("文件正在被其他用户编辑，请稍后再试。")
        return False
    lock.acquire()
    lock_timestamp = time.time()
    return True

def release_lock():
    global lock
    if lock.locked():
        lock.release()

st.title("在线编辑Excel文件")

# 上传Excel文件
uploaded_file = st.file_uploader("选择一个Excel文件", type=["xlsx", "xls"])

if uploaded_file is not None:
    if acquire_lock():
        try:
            # 读取Excel文件
            df = pd.read_excel(uploaded_file)

            # 显示数据表
            st.write("Excel数据：")
            edited_df = st.data_editor(df)

            # 提供下载编辑后的数据
            def to_excel(df):
                output = BytesIO()
                writer = pd.ExcelWriter(output, engine='xlsxwriter')
                df.to_excel(writer, index=False, sheet_name='Sheet1')
                writer.save()
                processed_data = output.getvalue()
                return processed_data

            st.download_button(
                label="下载编辑后的Excel文件",
                data=to_excel(edited_df),
                file_name='edited_file.xlsx',
                mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            )
        finally:
            release_lock()
